<template>
  <div class="divBox">
    <el-card class="box-card">
      <el-form inline size="small" @submit.native.prevent>
        <el-form-item label="保护点名称：">
          <el-input v-model="listPram.name" placeholder="请输入保护点名称" clearable class="selWidth" />
        </el-form-item>
        <el-form-item label="所属单位：">
          <el-select v-model="listPram.departmentId" placeholder="请选择" class="selWidth">
            <el-option :value="item.id" v-for="(item, index) in departmentData" :key="index"
              :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" size="mini" type="primary" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button icon="el-icon-delete" type="danger" size="mini" @click="removeAll()"
            v-hasPermi="['admin:protection:point:deleteIds']">批量删除</el-button>
        </el-form-item>
        <el-form-item class="el-form-item-align-right">
          <el-button icon="el-icon-circle-plus" size="mini" type="primary" @click="handlerOpenEdit(0)"
            v-hasPermi="['admin:protection:point:save']">添加保护点</el-button>
          <el-button icon="el-icon-download" size="mini" type="primary" @click="handlerExport(1)"
            v-hasPermi="['admin:protection:point:export']" style="margin-left:0;">批量导出</el-button>
          <el-upload class="upload-demo" style="display:inline-block!important;" action
            accept="application/xls,application/x-xls,application/zip,application/rar" :before-upload="onBeforeUpload"
            :http-request="handleUploadForm" :headers="myHeaders" :show-file-list="false">
            <el-button icon="el-icon-upload2" size="mini" type="primary"
              v-hasPermi="['admin:protection:point:import']">导入</el-button>
          </el-upload>
          <el-button icon="el-icon-download" size="mini" type="primary" @click="getMuBan('/保护点信息导入表.xls', '保护点信息导入模板')"
            style="margin-left:0;">导入模板下载</el-button>
        </el-form-item>
      </el-form>
      <el-table ref="multipleTable" :data="listData.list" v-loading="loading" row-key="getRowKeys"
        @select="handleCheckBox" @select-all="handleSelectAll" size="mini" @sort-change="handleSortChange"
        :header-cell-style="{ fontWeight: 'bold', background: '#f8f8f9', color: '#515a6e', height: '40px' }" border>
        <el-table-column type="selection" width="50" />
        <el-table-column prop="number" label="序号" width="50" sortable="custom" />
        <el-table-column label="保护点名称" prop="name" min-width="120" />
        <el-table-column label="所属单位" prop="departmentName" min-width="120" />
        <!--        <el-table-column label="类型" prop="typeText" min-width="120"/>-->
        <!--        <el-table-column label="分布区域" prop="area" min-width="120"/>-->
        <el-table-column label="坐标位置" prop="coordinateText" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.longitude }},{{ scope.row.latitude }}
          </template>
        </el-table-column>
        <el-table-column label="联系方式" prop="contactInformation" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.contactInformation }}
          </template>
        </el-table-column>
        <el-table-column label="保护半径" prop="radius" min-width="120" />
        <el-table-column label="备注" prop="remark" min-width="120" />
        <el-table-column label="操作" min-width="195" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button icon="el-icon-edit" type="primary" size="mini" @click="handlerOpenEdit(1, scope.row)"
              v-hasPermi="['admin:protection:point:info']">编辑</el-button>
            <el-button icon="el-icon-download" type="success" size="mini" @click="handlerExport(2, scope.row)"
              v-hasPermi="['admin:protection:point:export']">导出</el-button>
            <el-button icon="el-icon-delete" type="danger" size="mini" @click="handlerOpenDel(scope.row)"
              v-hasPermi="['admin:protection:point:delete']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination :current-page="listPram.page" :page-sizes="constants.page.limit" :layout="constants.page.layout"
        :total="listData.count" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>
    <el-dialog :visible.sync="editDialogConfig.visible" :title="editDialogConfig.isCreate === 0 ? '创建保护点' : '编辑保护点'"
      destroy-on-close :close-on-click-modal="false" width="700px">
      <edit v-if="editDialogConfig.visible" :is-create="editDialogConfig.isCreate"
        :edit-data="editDialogConfig.editData" :all-tree-list="treeList" :all-category-data="categoryData"
        @hideEditDialog="hideEditDialog" />
    </el-dialog>
  </div>
</template>

<script>
import * as protectionPointApi from '@/api/protectionPoint.js'
import * as roleApi from '@/api/role.js'
import edit from './edit'
import { checkPermi } from "@/utils/permission";
import * as selfUtil from "@/utils/ZBKJIutil";
import * as categoryApi from "@/api/categoryApi";
import { categoryPointList } from "@/api/categoryApi"; // 权限判断函数
import { createFile, exportTest } from '@/utils/utils'
import { getToken } from "@/utils/auth";
import { getDepartmentList } from '@/api/person'
import {typeDelBatch} from "@/api/protectionPoint.js";
export default {
  // name: "index"
  components: { edit },
  data() {
    return {
      departmentData: [],
      constants: this.$constants,
      loading: false,
      listData: { list: [] },
      listPram: {
        name: '',
        /*departmentId: null,
        ipAddress: null,
        macAddress: null,
        personId: null,*/
        page: 1,
        limit: this.$constants.page.limit[0]
      },
      editDialogConfig: {
        visible: false,
        isCreate: 0, // 0=创建，1=编辑
        editData: {}
      },
      treeList: [],
      categoryData: {},

      myHeaders: { "X-Token": getToken() },

      multipleSelection: [],//勾选的人员对象ID
    }
  },
  mounted() {
    this.handleGetPointList()
    this.initCategoryData()
    this.handlerGetTreeList() //所属单位
    this.getDepartmentList() //所属单位
  },
  methods: {
    handleSortChange(c) {
      const order = c.order;
      if (order == null || order == 'ascending') {
        this.listPram.sortType = 2;
      } else {
        this.listPram.sortType = 1;
      }
      this.handleGetPointList();
    },
    getDepartmentList() {
      getDepartmentList().then(res => {
        this.departmentData = res
      })
    },
    checkPermi,
    handleSearch() {
      this.listPram.page = 1
      this.handleGetPointList()
    },
    handleSizeChange(val) {
      this.listPram.limit = val
      this.handleGetPointList()
    },
    handleCurrentChange(val) {
      this.listPram.page = val
      this.handleGetPointList()
    },
    handlerOpenDel(rowData) {
      this.$confirm('确认删除当前数据').then(() => {
        const _pram = { id: rowData.id }
        protectionPointApi.pointDel(_pram).then(data => {
          this.$message.success('删除数据成功')
          this.handleGetPointList()
        })
      })
    },
    getMuBan(url, fileName) {
      exportTest(url, fileName);
    },
    //获取部门列表
    handlerGetTreeList() {
      const _pram = { name: '' }

      this.loading = true
      categoryApi.treeCategroy(_pram, 3).then(data => {
        this.treeList = this.handleAddArrt(data)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleAddArrt(treeData) {
      const _result = selfUtil.addTreeListLabel(treeData)
      return _result
    },
    initCategoryData() {
      this.loading = true

      categoryApi.categoryPointList().then(data => {
        this.categoryData = data
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleGetPointList() {
      protectionPointApi.pointList(this.listPram).then(data => {
        this.listData = data
      })
    },
    handlerOpenEdit(isCreate, editDate) {
      this.editDialogConfig.editData = editDate
      this.editDialogConfig.isCreate = isCreate
      this.editDialogConfig.visible = true
    },
    hideEditDialog() {
      this.editDialogConfig.visible = false
      this.handleGetPointList()
    },
    resetQuery() {
      this.listPram.name = '';
      this.listPram.departmentId = '';
      this.handleGetPointList()
    },

    //导入
    onBeforeUpload(file) {
      const isEXCEL = file.type === 'application/xls' || 'application/x-xls' || 'application/zip' || 'application/rar';
      const isLt1M = file.size / 1024 / 1024 < 100;

      if (!isEXCEL) {
        this.$message.error('上传文件只能是EXCEL格式!');
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 100MB!');
      }
      return isEXCEL && isLt1M;
    },
    // 上传
    handleUploadForm(param) {
      const formData = new FormData();
      formData.append("file", param.file);
      let loading = this.$loading({
        lock: true,
        text: "上传中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      protectionPointApi.doImport(formData)
        .then((res) => {

          let msg = "";
          this.$message.info(res);
          loading.close();

          this.handleGetPointList()
        })
        .catch((res) => {
          loading.close();
        });
    },


    //导出
    handlerExport(operateType, editData) {
      if (operateType === 1 && this.multipleSelection.length === 0) {
        this.$message.error("请在列表中勾选导出项")
        return
      }
      let loading = this.$loading({
        lock: true,
        text: "导出中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      let ids = ''
      if (operateType === 2) {
        ids = editData.id
      } else {
        ids = this.multipleSelection.join(',')
      }
      const _pram = { ids: ids }
      protectionPointApi.exportRoster(_pram)
        .then((res) => {
          if (!createFile(res, '保护点花名册')) {
            this.$message.success("未知的文件格式");
          }

          loading.close();
        })
        .catch((res) => {
          loading.close();
        });
    },
    //勾选/取消
    handleCheckBox(rows, row) {
      var index = this.multipleSelection.indexOf(row.id);
      if (index !== -1) {
        this.multipleSelection.splice(index, 1);
      } else {
        this.multipleSelection.push(row.id);
      }
    },
    //全部勾选/取消
    handleSelectAll(rows) {
      this.multipleSelection = []; // 清空数组
      if (rows.length > 0) {
        rows.forEach((row) => {
          this.multipleSelection.push(row.id);
        });
      } else {
        this.listData.list.forEach((row) => {
          this.multipleSelection = this.multipleSelection.filter(
            (item) => item != row.id
          )
        })
      }
    }
    ,
    //批量删除
    removeAll() {
      // 将 this.multipleSelection 赋值给变量 selectedIds
      // 弹出确认对话框并发送删除请求
      if (this.multipleSelection.length == 0) {
        this.$message.warning('请至少选择一条要删除的数据');
        return;
      }
      this.$confirm("确认要删除选中的" + this.multipleSelection.length + "条数据吗?").then(() => {
        const loading = this.$loading({ text: '删除中' });
        protectionPointApi.typeDelBatch({ ids: this.multipleSelection.join(',') }).then(() => {
          this.$message.success('删除成功');
          this.listPram.page = 1;
          this.handleGetPointList();
        }).finally(() => {
          loading.close();
        })
      })
    },
    //下面的方法是进行设置行标识key的方法
    getRowKeys(row) {
      return row.id
    },
    toggleSelection() {
      this.$refs.multipleTable.clearSelection();
    }
  }
}
</script>

<style scoped></style>
